#necessary libraries
from ftplib import FTP
import re, socket, sys, time
from getopt import getopt
import zipfile, zlib, uuid
#variables to upload file
path_in = "/django_projects/oursite/upload/"                 #path on the server
file_in = "stat.zip"                #file on the server to load 
file_err = "get_again.inf"          #local file information about errors
#variables to load file
path_out = "/django_projects/oursite/upload/"                #path on the server
path_loc = "./data/"                #local relative path
file_out = "stat.zip"               #local file to upload
#information for authentication  
ip_serv = "donkey.tophost.com.ua"   
login = 'dlyfar'                    
password = 'CcUDgjD'


file_exist = 0                      #flag of existence file on local machine or on server
socket.setdefaulttimeout(30)        #installation time limits
#=================================
#checking existence on the server
def list_filter(str):               
    global file_exist               
    m = re.match(".*\s"+re.escape(file_out)+"$", str)
    if m:
        file_exist = 1
#=================================
#upload file to server
def upload_fl():

    ftp = FTP(ip_serv)              #create a connection
    ftp.login(login,password)       #

    err = 0

    import uuid
    file = open('./data/info.txt','r')
    text = file.read()
    file.close()
    if text[5:]=='-1':
        id_pc = uuid.uuid1()
        file = open('./data/info.txt','w')
        file.write(text[:5]+str(id_pc))
        file.close()
    else:
        id_pc =text[5:]
    
    alfa = zipfile.ZipFile('./data/'+ str(id_pc) +'stat.zip','w',zipfile.ZIP_DEFLATED)
    alfa.write('./data/stat.xml', 'stat.xml')
    alfa.close()
    file_out2 = str(id_pc) + file_out
#checking the existence of a file on the server and removing it if it exists
    try:                        
        ftp.dir(path_out, list_filter)
        if file_exist:
            ftp.delete(path_out+file_out2)
    except socket.timeout, msg:
        err = 1
    except:
        err = 2
#opening the file flow and writing on the server
    if not err:
        fd = open(path_loc+file_out2, 'rb')
        try:
            ftp.storbinary("STOR "+path_out+file_out2, fd)
        except socket.timeout, msg:
            err = 1
        except:
            err = 2
        fd.close()
#closing connection and return value
    if not err:
        ftp.quit()
        return 0
    else:
        ftp.close()
        return 1
#=================================
#reading the file indicating the starting point if needed finish load file
def FromFtpToFile(ftpobj, ftpfile, desclocfile, pos=-1):
    tmp = 0
    try:
        if pos == -1:
            ftpobj.retrbinary("RETR "+ftpfile, desclocfile.write)
        else:
            ftpobj.retrbinary("RETR "+ftpfile, desclocfile.write, 8192, pos)
    except socket.timeout, msg:
        tmp = 1
    except:
        tmp = 2
    return tmp
#=================================
#load file from server
def load_fl():

    args = {}

    (optlist, a) = getopt(sys.argv[1:], 'ch', ['help', 'cont'])

    for (key, value) in optlist:
        args[key[key.rfind('-',0,3)+1:]] = value

    ftp = FTP(ip_serv)              #create a connection and
    ftp.login(login,password)       #               get the file size
    ftp_size = cur_size = ftp.size(path_in+file_in)

    err = 0                         
#load a file with the possibility dokachki
    if args.has_key("c") or args.has_key("cont"):
        fd = open(path_loc+file_in, 'ab')
        cur_size = fd.tell()
        if ftp_size > cur_size:
            err = FromFtpToFile(ftp, path_in+file_in, fd, cur_size)
            cur_size = fd.tell()
        elif ftp_size < cur_size:
            fd.close()
            fd = open(path_loc+file_in, 'wb')
            err = FromFtpToFile(ftp, path_in+file_in, fd)
            cur_size = fd.tell()
    
        fd.close()
#simple load a file
    else:
        fd = open(path_loc+file_in, 'wb')
        err = FromFtpToFile(ftp, path_in+file_in, fd)
        cur_size = fd.tell()
        fd.close()

#closing connection with handling errors and return value
    if not err:
        ftp.quit()
    else:
        ftp.close()
    
    if ftp_size != cur_size:
        fd = open(file_err, 'wb')
        fd.write(str(time.time()))
        fd.close()
        return 1
    else:
        return 0
#=================================
#test described functions
#print upload_fl()
#print load_fl() 
